#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

static int replace_string_substr(char *s, char *s1, char *s2)
{
    if(s==NULL || s1==NULL || s2==NULL)
        return -1;

    char *psubstr = NULL;
    int s1_len = strlen(s1);
    int s2_len = strlen(s2);
    if(s1_len < s2_len)
    {
        printf("s1 len[%d] < s2 len[%d] is unsafe!\n",s1_len,s2_len);
        return -1;
    }
    while((psubstr = strstr(s,s1)))
    {
        int i = 0;
        char *p = psubstr;
        char *q = psubstr+s1_len;
        for(; *p&& i<s2_len;p++,i++)
            *p = *s2++;
        for(;*q;q++)
            *p++ = *q;
        *p = '\0';
    }
    return 0;
}

int main(int argc, char *argv[])
{
	int ret = 0;
	char s[64]={0};
	char *s1 = "YYYY";
	char *s2 = "%Y";

	strcpy(s,"YYYYMMDD/hhmmss_nn.avi");
	printf("origin string: %s\n",s);
	ret = replace_string_substr(s,s1,s2);
	replace_string_substr(s,"MM","%m");
	replace_string_substr(s,"DD","%d");
	replace_string_substr(s,"hh","%H");
	replace_string_substr(s,"mm","%M");
	replace_string_substr(s,"ss","%S");
	//replace_string_substr(s,"nn","%d");
	printf("replace string[ret=%d]: %s\n",ret,s);

	time_t now = time(NULL);
	char buf[100]={0};

	strftime(buf,100,s,localtime(&now));
	printf("after strftime: %s\n",buf);

	return 0;
}

